package com.liusy.taskengine;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;


/**
 * 启动，加载配置类
 * 
 * @author liusy 2012-12-12
 *
 */
public class InitialTaskEngine {
	
   private static Logger log = Logger.getLogger(InitialTaskEngine.class);

   private static String  proxoolPath = System.getProperty("user.dir")+"/src/proxool.xml";
   
   private static String  taskEngineConfigPath =  System.getProperty("user.dir") + "/src/config.conf";


	/**
	 * 加载proxool驱动，并注册连接
	 * 
	 */
   private static void registerProxoolDriver()
	{
		try {
			if(ProxoolFacade.getAliases().length==0)
			{
				Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
				//JAXPConfigurator.configure(new InputStreamReader(JdbcHelp.class.getClassLoader().getResourceAsStream("proxool.xml")), false);
				//System.out.println(System.getProperty("user.dir")+"/src/proxool.xml");
				log.info("正 在注册数据库链接驱动 ：proxool path : "+System.getProperty("user.dir")+"/src/proxool.xml");
				JAXPConfigurator.configure(System.getProperty("user.dir")+"/src/proxool.xml", false);
				log.info("已经注册的数据库驱动："+Arrays.toString(ProxoolFacade.getAliases()));
			}
		} catch (ProxoolException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
   
   public static void initTaskEngine(String  proxoolPath,String  taskEngineConfigPath) {
	   
	   InitialTaskEngine.proxoolPath = proxoolPath;
	   InitialTaskEngine.taskEngineConfigPath = taskEngineConfigPath;
	   initTaskEngine();
	   
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				log.info("本次任务结束，欢迎下次使用！");
			}
		});
		
   }
   
	/**
	 * 初始化加载
	 * 
	 */
   public static void initTaskEngine() {
	   log.info("任务引擎   初始化...");
	   if(!new File(taskEngineConfigPath).exists())
	   {
		   log.error("   ["+taskEngineConfigPath+"] 文件不存在！");
		   new Throwable("   ["+taskEngineConfigPath+"] 文件不存在！");
		   System.exit(0);
	   }
      Properties props = readProperties(System.getProperty("user.dir") + "/src/config.conf");
      try {
		
		      //做DB任务时用的数据源          默认ComparisonTaskConnection
		     TaskEngineConstant.COMPARISON_TASK_CONNECTION = props.getProperty("liusy.taskengine.comparison_task_connection");
		      //做DB任务时查询从任务池中查询任务数据源          默认QueryTaskConnection
			 TaskEngineConstant.QUERY_TASK_CONNECTION = props.getProperty("liusy.taskengine.query_task_cnnection");
		      //执行器（工具）做任务的频率               默认1000
		     TaskEngineConstant.EXECUTE_TASK_RATE = Long.parseLong(props.getProperty("liusy.taskengine.execute_task_rate"));
		      //任务发布器，发布从缓存任务中发布任务的频率              默认300
		     TaskEngineConstant.RELEASE_TASK_RATE = Integer.parseInt(props.getProperty("liusy.taskengine.release_task_rate"));
		      //任务发布器，发布从缓存任务中发布任务的频率              默认100
		     TaskEngineConstant.TASK_EXECUTE_THREAD_MAX = Integer.parseInt(props.getProperty("liusy.taskengine.task_execute_thread_max"));
		 	  //当缓存中的任务少低于CACHE_TASK_LIMIT时，任务发布器将从任务池中再次获取任务，再进行发布
		     TaskEngineConstant.CACHE_TASK_LIMIT = Integer.parseInt(props.getProperty("liusy.taskengine.cache_task_limit"));
		 	  //监控CACHE_TASK_LIMIT频率
		 	 TaskEngineConstant.MONITOR_CACHE_TASK_LIMIT_RATE= Integer.parseInt(props.getProperty("liusy.taskengine.monitor_cache_task_limit_rate"));
	 	 
	  	} catch (Exception e) {
	  	  log.error("["+taskEngineConfigPath+"] 文件中参数错误!!请检查！");
		  System.exit(0);
		}
      
	   String [] aliases = ProxoolFacade.getAliases();
	   log.info("已经注册的数据库驱动："+Arrays.toString(aliases));
	   Arrays.sort(aliases);
	   if(Arrays.binarySearch(aliases, TaskEngineConstant.COMPARISON_TASK_CONNECTION)<0||Arrays.binarySearch(aliases, TaskEngineConstant.QUERY_TASK_CONNECTION)<0)
	   {
		   if(!new File(taskEngineConfigPath).exists())
		   {
			   log.error("   ["+taskEngineConfigPath+"] 文件不存在！");
			   new Throwable("   ["+taskEngineConfigPath+"] 文件不存在！");
			   System.exit(0);
		   }
		   registerProxoolDriver();
	   }
      log.info("任务引擎  初始化结束.");
   }
   
   
   /**
    * 读配置文件 
    * 
    * @param filePath  文件路径
    * @return
    */
   private static Properties readProperties(String filePath) {
      Properties props = new Properties();
      try {
         InputStream in = new BufferedInputStream(new FileInputStream(filePath));
         props.load(in);
      }
      catch (Exception e) {
         e.printStackTrace();
      }
      return props;
   }
   
   

   /**
    * 写入properties信息
    * 
    * @param filePath  路径
    * @param parameterName  key
    * @param parameterValue value
    */
   private static void writeProperties(String filePath, String parameterName, String parameterValue) {
      Properties prop = new Properties();
      try {
         InputStream fis = new FileInputStream(filePath);
         prop.load(fis);
         OutputStream fos = new FileOutputStream(filePath);
         prop.setProperty(parameterName, parameterValue);
         prop.store(fos, "Update '" + parameterName + "' value");
      }
      catch (IOException e) {
         System.err.println("Visit " + filePath + " for updating " + parameterName + " value error");
      }
   }
   

}
